//通用中间件
const createError = require('http-errors'),
    express = require('express'),
    path = require('path'),
    cookieParser = require('cookie-parser'),
    logger = require('morgan'),
    bodyParser = require('body-parser'),

    //引入路由
    indexRouter = require('./routes/index'),

    //初始化APP
    app = express(),
    //获取普通access_token,生成菜单
    getCommonAccessToken = require('./common/getCommonAccessToken'),
    buildMenu = require('./common/buildMenu');
require('body-parser-xml')(bodyParser);

getCommonAccessToken();
buildMenu();

//设置页面路径及模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//调用通用中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

//设置静态文件目录
app.use(express.static(path.join(__dirname, 'public'),{index: false}));
//解析xml
app.use(bodyParser.xml({
    limit: '1MB',
    xmlParseOptions: {
        normalize: true,
        normalizeTags: true,
        explicitArray: false
    }
}));

//使用路由
//微信验证开发者服务器
app.use(indexRouter);


//捕获错误
app.use(function(req, res, next) {
    next(createError(404));
});

//处理错误
app.use(function(err, req, res, next) {
    console.log('>>>>发生错误<<<<',err)
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
